package com.py.comment.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.py.apis.article.IArticleClient;
import com.py.apis.article.IuserClitent;
import com.py.comment.mapper.CommentMapper;
import com.py.comment.service.CommentService;
import com.py.common.redis.CacheService;
import com.py.model.common.dtos.ResponseResult;
import com.py.model.moment.dtos.CommentDto;
import com.py.model.moment.dtos.CommentLikeDto;
import com.py.model.moment.dtos.CommentSaveDto;
import com.py.model.moment.pojos.Comment;
import com.py.model.moment.pojos.CommentLike;
import com.py.model.user.pojos.ApUser;
import com.py.utils.common.ApUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author pengy
 * @create 2022-11-16 20:22
 */
@Service
@Slf4j
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Autowired
    private IArticleClient iArticleClient;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IuserClitent iuserClitent;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 保存评论到mongoDB
     *
     * @param dto
     */
    @Override
    public void saveToMongo(CommentSaveDto dto) {

        boolean flag = iArticleClient.query(dto);
        if (!flag) {
            log.info("该文章不可评论");
            return;
        }
        Integer userId = ApUserThreadLocalUtil.get().getId();
        //可评论并且已上架 保存评论到mongo
        Comment comment = new Comment();
        comment.setUserId(userId);
        //查询获取apuser详细信息
        ApUser apUser = iuserClitent.get(userId);
        comment.setLikes(0);//点赞数为0
        comment.setAuthorName(apUser.getName());
        comment.setImage(apUser.getImage());
        comment.setCreatedTime(new Date());
        comment.setContent(dto.getContent());
        comment.setArticleId(dto.getArticleId());
        comment.setReply(0);//发表评论 的是默认是0 回复
        comment.setUpdatedTime(new Date());
        comment.setOperation(1); //是否点赞//0标识被当前用户点赞了    1 标识 该评论没有被当前用户点赞

        mongoTemplate.save(comment);
    }

    /**
     * 分页展示评论列表
     *
     * @param commentDto
     * @return
     */
    @Override
    public ResponseResult loadPage(CommentDto commentDto) {
        //前端问题,加锁解决前端连续发送两次请求
        String lockflag = cacheService.tryLock("task-loadPage",3000);
        if(lockflag == null){
            log.info("未获取到锁，不执行");
            return ResponseResult.okResult(null);
        }

        //如果是以第一次过来查询 那么传递一个null时间
        if (commentDto.getMinDate() == null) {
            commentDto.setMinDate(new Date());
        }

        //查询条件1
        Query query = Query.query(
                Criteria.where("articleId").is(commentDto.getArticleId())
                        .and("createdTime").lt(commentDto.getMinDate())
        );
        //排序条件2
        Sort sort = Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        //限制条件3
        query.limit(10);

        List<Comment> comments = mongoTemplate.find(query, Comment.class);

        return ResponseResult.okResult(comments);
    }

    /**
     * 点赞评论或者取消点赞
     *
     * @param commentLikeDto
     */
    @Override
    public ResponseResult like(CommentLikeDto commentLikeDto) {

        Integer userId = ApUserThreadLocalUtil.get().getId();

        //校验参数
        if (commentLikeDto.getOperation() == 0) {
            //点赞操作
            //先查询 如果有点赞记录 不用点赞了
            Query query = Query.query(Criteria.where("userId").is(userId)
                    .and("commentId").is(commentLikeDto.getCommentId()));
            List<CommentLike> commentLikes = mongoTemplate.find(query, CommentLike.class);
            if (commentLikes != null && commentLikes.size() > 0) {
                log.info("该评论已经点赞:{}", commentLikes);
                //删除记录,取消点赞
                mongoTemplate.remove(query, CommentLike.class);
                //返回
                Comment comment = mongoTemplate.findById(commentLikeDto.getCommentId(), Comment.class);
                comment.setOperation(1);
                mongoTemplate.save(comment);
                return ResponseResult.okResult(comment);
            }
            //保存点赞记录
            CommentLike commentLike = new CommentLike();
            commentLike.setCommentId(commentLikeDto.getCommentId());
            commentLike.setUserId(userId);
            //插入到MongoDB
            mongoTemplate.insert(commentLike);

            //找到这个评论 需要将点赞数量加 1
            Comment comment = mongoTemplate.findById(commentLikeDto.getCommentId(), Comment.class);
            comment.setLikes(comment.getLikes() + 1);
            comment.setOperation(1);
            mongoTemplate.save(comment);
        } else {
            //取消点赞
            //删除这条点赞记录
            Query query = Query.query(Criteria.where("userId").is(userId)
                    .and("commentId").is(commentLikeDto.getCommentId()));
            mongoTemplate.remove(query, CommentLike.class);


            //找到这个评论点赞数减 1
            Comment comment = mongoTemplate.findById(commentLikeDto.getCommentId(), Comment.class);
            comment.setLikes(comment.getLikes() - 1);
            comment.setOperation(0);
            mongoTemplate.save(comment);

        }

        Comment comment = mongoTemplate.findById(commentLikeDto.getCommentId(), Comment.class);
        return ResponseResult.okResult(comment);

    }
}
